package com.xc.quickstart.mq.producer;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.xc.quickstart.common.bean.ExceptionDelayQueueProcessor;
import com.xc.quickstart.common.context.ApiContext;
import com.xc.quickstart.common.event.ExceptionDelayQueueEvent;
import com.xc.quickstart.common.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.time.Instant;

/**
 * @author yinyansheng
 */
@Slf4j
public abstract class BaseMqProducer {

    @Autowired
    private ExceptionDelayQueueProcessor exceptionDelayQueueProcessor;

    public ApiResponse produce(String message) {
        try {
            log.info("[消息发送][{}]开始,message:{},crmTraceId:{}", getProducerName(), message, ApiContext.getCrmTraceId());

            Instant start = Instant.now();
            Message msg = new Message(getTopic(), getTags(), message.getBytes());
            SendResult result = this.getProducer().send(msg);

            log.info("[消息发送][{}]结束,message:{},result:{},耗时:{}ms,crmTraceId:{}"
                    , getProducerName()
                    , message
                    , JSON.toJSONString(result)
                    , Duration.between(start, Instant.now()).toMillis()
                    , ApiContext.getCrmTraceId());

            return ApiResponse.ok(result);
        } catch (Exception ex) {
            log.error("[消息发送][{}]异常;message:{};ex:{},crmTraceId:{}"
                    , getProducerName()
                    , message
                    , ExceptionUtil.stacktraceToString(ex)
                    , ApiContext.getCrmTraceId());

            exceptionDelayQueueProcessor.put(new ExceptionDelayQueueEvent(this.getClass().getName(), getProducerName(), ExceptionUtil.stacktraceToString(ex, 400)));
            return ApiResponse.fail();
        }
    }


    public abstract Producer getProducer();

    public abstract String getTopic();

    protected abstract String getProducerName();

    protected String getTags() {
        return "";
    }

}
